/**
 * Created by YJH on 2018/5/30.
 */

import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    Alert,
} from 'react-native';
import CheckBox from 'react-native-check-box';
import NavigationBarComponent from '../NavigationBarComponent';
import Toast, {DURATION} from 'react-native-easy-toast';
import NavigationBarUtil from '../../util/NavigationBarUtil';
import ArrayUtil from '../../util/ArrayUtil';
import LanguageDao, {FLAG_LAN} from '../../expand/dao/LanguageDao';

const KEY = 'KEY-Async';
export default class TabCustomPage extends Component {

    constructor(props) {
        super(props);
        this.isRemove = this.props.isRemove;
        this.languageDao = this.props.isPopular?new LanguageDao(FLAG_LAN.flagKey):new LanguageDao(FLAG_LAN.flagLanguage);
        this.checkboxChangeValues = [];

        this.state = {
            inputTxt: '',
            txtFetch: '点击拉取数据',
            dataArray: [],
            theme:this.props.theme,
        }

    }

    componentDidMount() {
        this.loadDataFromLanguageDao();
    }

    loadDataFromLanguageDao() {
        this.languageDao.fetch()
            .then(result => {
                this.setState({
                    dataArray: result,
                });
            }).catch(error => {
            console.log(error);
        })
    }

    onSave(isBack) {
        if (isBack) {
            if (this.checkboxChangeValues.length !== 0) {
                // Works on both iOS and Android
                Alert.alert(
                    '提醒',
                    '标签状态已修改，是否保存？',
                    [
                        // {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
                        {
                            text: '取消', onPress: () => {
                            this.props.navigator.pop();
                        }, style: 'cancel'
                        },
                        {
                            text: '保存', onPress: () => {
                            this.languageDao.save(this.state.dataArray);
                            this.props.navigator.pop();
                        }
                        },
                    ],
                    {cancelable: false}
                );

            } else {
                this.props.navigator.pop();
            }

        } else {
            if (this.checkboxChangeValues.length !== 0) {
                if (this.isRemove) {
                    for (let i = 0, len = this.checkboxChangeValues.length; i < len; i++) {
                        ArrayUtil.remove(this.state.dataArray, this.checkboxChangeValues[i]);
                    }
                }

            }

            this.languageDao.save(this.state.dataArray);
            // this.toast.show(this.state.dataArray[0].name);
            // this.toast.show(this.checkboxChangeValues[0].name);
            this.props.navigator.pop();
        }


    }


    scrollViewRender() {
        if (!this.state.dataArray || this.state.dataArray.length === 0) {
            return null;
        }
        let len = this.state.dataArray.length;
        let views = [];
        for (let i = 0, l = len - 2; i < l; i += 2) {
            views.push(
                <View key={i}>
                    <View style={styles.view_row}>
                        {this.setCheckBox(this.state.dataArray[i])}
                        {this.setCheckBox(this.state.dataArray[i + 1])}
                        {/*<Text style={{alignSelf: 'center'}}>{this.state.dataArray[i].name}</Text>*/}
                        {/*<Text style={{alignSelf: 'center'}}>{this.state.dataArray[i + 1].name}</Text>*/}
                    </View>
                    <View style={{height: 1, backgroundColor: 'gray', flex: 1}}/>
                </View>
            )
        }

        views.push(
            <View key={len - 1}>
                <View style={styles.view_row}>
                    {len % 2 === 0 ? this.setCheckBox(this.state.dataArray[len - 2]) : null}
                    {this.setCheckBox(this.state.dataArray[len - 1])}
                </View>
                <View style={{height: 1, backgroundColor: 'gray', flex: 1}}/>
            </View>);
        return views;
    }

    setCheckBox(data) {
        const isChecked=this.isRemove?false:data.checked;
        return <CheckBox style={{flex: 1, marginHorizontal: 10}}
                         onClick={() => {
                             this.onClick(data)
                         }}
                         leftText={data.name}
                         isChecked={isChecked}
                         checkedImage={<Image style={{tintColor: this.state.theme.themeColor, width: 20, height: 20}}
                                              source={require('../../../res/images/ic_btn_check_checked.png')}/>}
                         unCheckedImage={<Image style={{tintColor: 'gray', width: 20, height: 20}}
                                                source={require('../../../res/images/ic_btn_check_normal.png')}/>}
        />
    }


    onClick(data) {
        if (!this.isRemove) {
            //如果是进行自定义标签的操作
            data.checked = !data.checked;
        }
        ArrayUtil.updateArray(this.checkboxChangeValues, data);

    }

    render() {
        const Title = this.props.menuType;
        // const Title = this.isRemove ? '移除标签' : '自定义标签';
        const RightButton = this.isRemove ? '移除' : '保存';

        return <View style={styles.container}>
            <NavigationBarComponent
                title={Title}
                style={this.state.theme.styles.navBar}
                statusBar={{backgroundColor:this.state.theme.themeColor}}
                leftButton={NavigationBarUtil.getLeftButton(() => this.onSave(true))}
                rightButton={NavigationBarUtil.getRightButtonWord(() => this.onSave(false), RightButton)}
            />
            <ScrollView>
                {this.scrollViewRender()}
            </ScrollView>


            <Toast ref={toast => this.toast = toast}/>
        </View>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FCFCFC',
    },

    container_row: {
        backgroundColor: '#FCFCFC',
        flexDirection: 'row',
        alignItems: 'center',
    },

    btn: {
        height: 60,
        margin: 5,
        borderWidth: 10,
        justifyContent: 'space-between',
        alignSelf: 'center',
        marginHorizontal: 15,
    },

    edt: {
        marginTop: 50,
        height: 60,
        marginHorizontal: 15,
    },
    view_row: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 60,
        justifyContent: 'space-between',
        marginHorizontal: 15,
    }
});